package Util.Map;

import java.util.Collection;
import java.util.Objects;
import java.util.Set;

public interface Map<K, V> {
    int size();
    boolean isEmpty();
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    V get(Object key);
    V put(K key, V value);
    V remove(Object key);
    void putAll(Map<? extends K, ? extends V> m);
    void clear();

    Set<K> keySet();
    Collection<V> values();
    Set<Map.Entry<K, V>> entrySet();

    @Override
    boolean equals(Object o);
    @Override
    int hashCode();


    interface Entry<K, V>{
        K getKey();
        V getValue();
        V setValue(V value); //返回旧值
        @Override
        boolean equals(Object o);
        @Override
        int hashCode();
    }

    default V getOrDefault(Object key, V defaultValue){
        return containsKey(key) ? get(key) : defaultValue;
    }

    default boolean remove(K key, V value){
        if(!containsKey(key)) {
            return false;
        }
        Object curValue = get(key);
        return Objects.equals(curValue, value);
    }

    default boolean replace(K key, V oldValue, V newValue) {
        if (!containsKey(key) || !Objects.equals(oldValue, get(key))) {
            return false;
        }
        put(key, newValue);
        return true;
    }

    default V replace(K key, V value){
        if(containsKey(key)){
            return put(key, value);
        }else{
            return null;
        }
    }

    default V putIfAbsent(K key, V value){
        V v = get(key);
        if(v == null){
            v = put(key, value);
        }
        return v;
    }

}
